package com.rao.security.service;

import com.rao.security.entity.SysRole;
import com.rao.security.entity.SysUser;
import com.rao.security.mapper.SysRoleMapper;
import com.rao.security.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 登录业务处理
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/09/06 21:25
 */
@Service("jdbcUserDetatilsService")
public class JdbcUserDetatilsService implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据 username 获取 SysUser
        SysUser user = userMapper.selectSysUser(username);
        System.out.println("loadUserByUsername user:" + user);

        if (user != null) {
            //2.根据userId 获取 role
            List<SysRole> roleList = roleMapper.selectRoleByUser(user.getId());
            System.out.println("roleList:" + roleList);

            List<GrantedAuthority> authorities = new ArrayList<>();
            String roleName = "";
            for (SysRole role : roleList) {
                roleName = role.getRoleName();
                GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + roleName);
                authorities.add(authority);
            }
            user.setAuthorities(authorities);
        }
        return user;
    }

}
